import  {randomUUID} from 'crypto'
import {TRPCError} from '@trpc/server'
import dayjs from 'dayjs'

// 抛出一个Trpc的业务异常
export const createTrpcError = (msg: string) =>{
  return new TRPCError({
    code: 'BAD_REQUEST',
    message: msg,
  })
}
/**
 * 获取uuid
 * @param replace 是否替换-
 * @returns 
 */
export const getUUID = (replace: boolean=false) => {
    return  replace ? randomUUID().replaceAll('-', '') : randomUUID()
}

// server/utils/filterUndefined.ts
export const filterUndefined = <T extends Record<string, any>>(obj: T): Partial<T> => {
    return Object.entries(obj).reduce((acc, [key, value]) => {
      if (value !== undefined) {
        acc[key as keyof T] = value;
      }
      return acc;
    }, {} as Partial<T>);
  };


interface CommunityData {
  unityCommunityId: string;
  unityCommunityName: string;
}

// 假设xiaoquRoot是全局可用的社区数据数组
declare const xiaoquRoot: CommunityData[];

/**
 * 解析/设置表单信息
 * @param s 原始数据
 * @return 处理后的表单数据映射
 */
export const   ajkForm2Map =(s: any): { [key: string]: string } =>{
  const bodyObj: { [key: string]: string } = {};
  
  // 解析JSON字符串
  const entries = s;
  
  // 获取各层级数据
  const params = entries.attr as Record<string, any>;
  // const params = data.attr as Record<string, any>;
  
  // 处理参数
  const keys = Object.keys(params);
  for (const key of keys) {
    const paramsJson = params[key] as Record<string, any>;
    const value = paramsJson.value as string;
    
    if (value && value.trim() !== '') {
      bodyObj[key] = value;
    }
  }
  
  // 添加固定字段
  bodyObj.from = 'hugList';
  bodyObj.params_200 = dayjs().format('YYYY-MM-DD');
  bodyObj.sw_realHouseCheck_uuid = entries.sw_realHouseCheck_uuid;
  
  // 处理小区信息
  const xiaoquId = bodyObj.xiaoquId;
  if (!xiaoquId) {
    throw createTrpcError('配置信息没有xiaoquId');
  }
  // 设置最早入住时间为今天
  // bodyMap.set('params_86', '小区名称可以不要');
  return bodyObj;
}

const parseJjauthCK = (ck: string) =>{
  const cookieObj: Record<string, string> = {};
  const ckStr = ck.split(',')[0]?.split(';')[0]
 cookieObj['jjrAuthTicket'] = ckStr?.substring(12) as string
 return cookieObj
}

export const  parseCookie = (cookieString: string): Record<string, string> =>{
  const cookieObj: Record<string, string> = {};
  
  // 处理空字符串情况
  if (!cookieString || typeof cookieString !== 'string') {
    return cookieObj;
  }
  // 解析固定的jjrAuthTicket
  // if(cookieString.indexOf('jjrAuthTicket') !== -1){
  //   return parseJjauthCK(cookieString)

  // }
  // 第一步：按逗号分割出单个Cookie项（处理后去除前后空格）
  const cookieItems = cookieString.split(',').map(item => item.trim());
  
  cookieItems.forEach(item => {
    // 跳过空项
    if (!item) return;
    
    // 第二步：按分号分割，安全获取第一个部分
    const parts = item.split(';');
    // 检查分割结果是否有至少一个元素
    if (!parts || parts.length === 0) return;
    
    const keyValuePart = parts[0]?.trim();
    // 跳过空的键值部分
    if (!keyValuePart) return;
    
    // 第三步：按等号分割键和值
    const [key, ...valueParts] = keyValuePart.split('=');
    // 确保键存在且值部分至少有内容
    if (!key || valueParts.length === 0) return;
    
    // 处理值中可能包含等号的情况
    const value = valueParts.join('=').trim();
    cookieObj[key] = value;
  });
  
  return cookieObj;
}